import axios from 'axios'
import Redirect from '../../router/Redirect'

import { history } from './history'

import React from 'react'


const http = axios.create({
  baseURL: 'http://localhost:8081',
  headers: { 'Content-Type': 'application/json' },
  responseEncoding: 'utf8',
  responseType: 'json',
})
// 添加请求拦截器
http.interceptors.request.use((config) => {
  config.headers['Content-Type'] = 'application/json'
  config.headers['satoken'] = localStorage.getItem("satoken")
  return config
}, (error) => {
  return Promise.reject(error)
})

// 添加响应拦截器
http.interceptors.response.use((response) => {

  let msg = response.data.msg
  if (msg !== undefined) {
    if (msg.indexOf("token") !== -1) {
      history.replace("/login")
    } else {
      return response
    }
  } else {
    if (response.msg.indexOf("token") !== -1) {
      history.replace("/login")
    } else {
      return response
    }
  }

}, (error) => {

  if (error && error.response && error.response.status) {
    if (error.response.status === 401 || error.response.status) {
      <Redirect to="/login" />
    }
  }
  return Promise.reject(error)
})

export { http }
